import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart';
import '../stores/chat_store.dart';
import '../widgets/avatar_widget.dart';

// 聊天列表页面
class ChatListScreen extends StatelessWidget {
  const ChatListScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // 获取ChatStore实例
    final chatStore = Provider.of<ChatStore>(context);

    return Scaffold(
      appBar: AppBar(
        title: const Text('聊天'),
        actions: [
          IconButton(
            icon: const Icon(Icons.search),
            onPressed: () {
              // TODO: 实现搜索功能
            },
          ),
          IconButton(
            icon: const Icon(Icons.add_circle_outline),
            onPressed: () {
              // TODO: 实现添加聊天功能
            },
          ),
        ],
      ),
      // 使用Observer监听状态变化
      body: Observer(
        builder: (_) {
          // 如果聊天列表为空，显示空状态
          if (chatStore.chatList.isEmpty) {
            return const Center(
              child: Text('暂无聊天', style: TextStyle(fontSize: 16)),
            );
          }

          // 显示聊天列表
          return ListView.builder(
            itemCount: chatStore.chatList.length,
            itemBuilder: (context, index) {
              final chat = chatStore.chatList[index];

              return ChatListItemWidget(
                chatItem: chat,
                onTap: () {
                  // 跳转到聊天详情页
                  context.go('/chat/${chat.id}');
                },
              );
            },
          );
        },
      ),
    );
  }
}

// 聊天列表项组件
class ChatListItemWidget extends StatelessWidget {
  final dynamic chatItem; // 聊天项数据
  final VoidCallback onTap; // 点击回调

  const ChatListItemWidget({
    Key? key,
    required this.chatItem,
    required this.onTap,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // 格式化最后消息时间
    String formattedTime = _formatTime(chatItem.lastMessageTime);

    return ListTile(
      // 点击回调
      onTap: onTap,
      // 头像
      leading: AvatarWidget(
        imageUrl: chatItem.avatar,
        isOnline: chatItem.isOnline,
        size: 48,
      ),
      // 标题 - 聊天对象名称
      title: Text(
        chatItem.name,
        style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
      ),
      // 副标题 - 最后一条消息
      subtitle: Text(
        chatItem.lastMessage,
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
        style: const TextStyle(fontSize: 14, color: Colors.grey),
      ),
      // 尾部 - 显示时间和未读数
      trailing: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          // 时间
          Text(
            formattedTime,
            style: const TextStyle(fontSize: 12, color: Colors.grey),
          ),
          const SizedBox(height: 4),
          // 未读消息提示
          if (chatItem.unreadCount > 0)
            Container(
              width: 20,
              height: 20,
              decoration: const BoxDecoration(
                color: Colors.red,
                shape: BoxShape.circle,
              ),
              child: Center(
                child: Text(
                  chatItem.unreadCount > 99
                      ? '99+'
                      : chatItem.unreadCount.toString(),
                  style: const TextStyle(fontSize: 10, color: Colors.white),
                ),
              ),
            ),
        ],
      ),
    );
  }

  // 格式化时间
  String _formatTime(DateTime time) {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    final yesterday = today.subtract(const Duration(days: 1));
    final messageDate = DateTime(time.year, time.month, time.day);

    if (messageDate == today) {
      // 今天 - 显示时间
      return DateFormat('HH:mm').format(time);
    } else if (messageDate == yesterday) {
      // 昨天 - 显示"昨天"
      return '昨天';
    } else if (now.difference(time).inDays < 7) {
      // 一周内 - 显示星期几
      return DateFormat('EEEE', 'zh_CN').format(time);
    } else {
      // 更早 - 显示日期
      return DateFormat('yyyy/MM/dd').format(time);
    }
  }
}
